package com.haima.sage.bigdata.api.frame.interpreter;

import java.util.ArrayList;
import java.util.List;

import com.haima.sage.bigdata.api.frame.interpreter.impl.DateValueService;
import com.haima.sage.bigdata.api.frame.interpreter.impl.FieldValueService;
import com.haima.sage.bigdata.api.frame.interpreter.impl.MultiValueService;
import com.haima.sage.bigdata.api.frame.interpreter.impl.NoneValueService;
import com.haima.sage.bigdata.api.frame.interpreter.impl.StaticValueService;


public class ValueServiceFactory {

    public static ValueService getInstance(String template) {
        if (template == null || 0 == template.length()) {
            return new NoneValueService();
        }
        if (!template.contains("$")) {
            return new StaticValueService(template);
        }
        if (template.startsWith("$")) {
            template = template.substring(1);
        }
        // /opt/${}/${}
        String[] arr = template.split("\\$");
        if (arr.length == 0) {
            return new NoneValueService();
        }
        List<ValueService> services = new ArrayList<>();
        for (String str : arr) {
            if (str.startsWith("{")) {
                if (str.endsWith("}")) {
                    services.add(getFieldService(str));
                } else {
                    int index = str.indexOf("}");
                    if (index != -1) {
                        String key1 = str.substring(0, index + 1);
                        services.add(getFieldService(key1));
                        String key2 = str.substring(index + 1);
                        services.add(new StaticValueService(key2));
                    }
                }
            } else {
                services.add(new StaticValueService(str));
            }

        }
        if (services.size() == 1) {
            return services.get(0);
        } else {
            return new MultiValueService(services);
        }
    }


    private static ValueService getFieldService(String str) {
        ValueService service = null;
        String[] items = str.substring(1, str.length() - 1).split(":");
        if (items.length != 0) {
            if (items.length == 1) {
                if (notEmpty(items[0])) {
                    service = new FieldValueService(items[0]);
                }
            } else if (items.length == 2) {
                if (notEmpty(items[0])) {
                    if (notEmpty(items[1])) {
                        service = new DateValueService(items[0], items[1]);
                    } else {
                        service = new FieldValueService(items[0]);
                    }
                }
            }
        }
        return service;
    }

    private static boolean notEmpty(String raw) {
        if (raw == null) {
            return false;
        }
        return raw.length() != 0;
    }
}
